package com.tos.second.interceptor;


import com.tos.second.common.basecontext.BaseContext;
import com.tos.second.common.constant.JwtClaimsConstant;
import com.tos.second.common.exception.BaseException;
import com.tos.second.entity.User;
import com.tos.second.mapper.UserMapper;
import com.tos.second.properties.JwtProperties;
import com.tos.second.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;// jwt配置

    @Autowired
    private UserMapper userMapper;


    @Autowired
    private RedisTemplate redisTemplate;//


    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断当前拦截到的是 Controller 的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            // 当前拦截到的不是动态方法，直接放行
            return true;
        }
        String ipAddress = getClientIpAddress(request);

        // 1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getTokenName());
        if (token == null || token.isEmpty()) {
            response.setStatus(401);
            return false;
        }

        // 2、校验令牌
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            Long id = Long.valueOf(claims.get(JwtClaimsConstant.ID).toString());
            // 获取tokenId
            String tokenId = claims.getId();
            // 从Redis中获取当前用户的tokenId
            String redisKey1 = "user:" + id + ":tokenId";
            String storedTokenId = (String) redisTemplate.opsForValue().get(redisKey1);

            // 校验当前tokenId与Redis中的tokenId是否一致
            if (storedTokenId == null || !storedTokenId.equals(tokenId)) {
                response.setStatus(401);
                throw new BaseException("您的账号已在其他设备登录");
            }

            // 从 Redis 中获取用户信息
            String redisKey = "user:" + id;
            User user = (User) redisTemplate.opsForValue().get(redisKey);
            if (user == null) {
                // 如果 Redis 中没有用户信息，则从数据库中查询
                user = userMapper.getById(id);
                if (user == null) {
                    throw new BaseException("用户不存在");
                }


                // 将用户信息存入 Redis，设置一个合适的过期时间
                redisTemplate.opsForValue().set(redisKey, user, jwtProperties.getTtl(), TimeUnit.MILLISECONDS);
            }

            // 检查用户状态
            if (user.getStatus() == 0) {
                throw new BaseException("账号已被禁用，请联系管理员");
            }

            // 设置当前登录用户的上下文
            BaseContext.setCurrentId(id);
            
            //打印用户信息，便于查询操作
            log.info("当前操作用户为：{}，请求ip为：{}",user.getName(),ipAddress);
            // 3、通过，放行
            return true;
        } catch (Exception ex) {
            // 4、不通过，响应401状态码
            response.setStatus(401);
            throw new BaseException("令牌无效");
        }
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.remove();
    }

    private String getClientIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }


}
